import 'package:flutter/material.dart';
import 'package:hm_pda_app/pages/camera_upload_widget.dart';
import 'package:hm_pda_app/components/loading_overlay.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:provider/provider.dart';

class PendingReinspectionScreen extends StatefulWidget {
  const PendingReinspectionScreen({super.key});

  @override
  State<PendingReinspectionScreen> createState() =>
      _PendingReinspectionScreenState();
}

class _PendingReinspectionScreenState extends State<PendingReinspectionScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('复检')),
      body: ReinspectionFormScreen(),
    );
  }
}

// 复检表单页面
class ReinspectionFormScreen extends StatefulWidget {
  const ReinspectionFormScreen({super.key});

  @override
  State<ReinspectionFormScreen> createState() => _ReinspectionFormScreenState();
}

class _ReinspectionFormScreenState extends State<ReinspectionFormScreen> {
  final _formKey = GlobalKey<FormState>(); // 表单Key
  final GlobalKey<_ReinspectionFormScreenState> formKey =
      GlobalKey<_ReinspectionFormScreenState>();
  // 定义一个对象
  PendingReinspection? _pendingReinspection;
  // 文本输入控制器

  final _qualityInspectionController = TextEditingController();

  final _reInspectionController = TextEditingController();
  final _badGoodController = TextEditingController();
  final _skuController = TextEditingController();
  // 请求接口
  Future<void> getInfo(BuildContext context) async {
    try {
      // 如果没有传入参数，使用控制器的值
      final finalIncomingGoodsNo = _qualityInspectionController.text;
      final finalSkuCode = _skuController.text;

      if ((finalIncomingGoodsNo.isEmpty) && (finalSkuCode.isEmpty)) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('请输入来货单号或sku编码'),
            duration: Duration(seconds: 1),
          ),
        );
        return;
      }

      LoadingOverlay.show(context);
      final response = await HttpUtil.post(
        '/storage/qualityCheckOperate/getLastOrder',
        data: {
          'incomingGoodsNo': finalIncomingGoodsNo,
          'skuCode': finalSkuCode,
          'whetherLastFinishOrder': false,
        },
      );

      // 处理响应数据
      if (response.data != null) {
        final dataMap = response.data as Map<String, dynamic>;
        print('查看复检信息---$dataMap');
        if (dataMap['data'] != null) {
          setState(() {
            _pendingReinspection = PendingReinspection.form(response.data);
          });
        } else {
          print('查看复检信息为空---$dataMap');
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('查询失败: 暂无数据'),
              duration: Duration(seconds: 3),
            ),
          );
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('查询失败: ${response.message}'),
            duration: Duration(seconds: 1),
          ),
        );
      }
    } catch (e) {
      print('查看复检信息---$e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('查询出错: $e'), duration: Duration(seconds: 1)),
      );
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 提交表单方法
  Future<void> _submitForm() async {
    try {
      LoadingOverlay.show(context);
      _submitFile();
      final response = await HttpUtil.post(
        '/storage/qualityCheckOperate/recheck',
        data: {
          'id': _pendingReinspection?.id,
          'recheckNum': _reInspectionController.text,
          'recheckDefectiveNum': _badGoodController.text,
          'recheckProblemDesc': null,
        },
      );
      print('提交复检---$response');
      if (response.success) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('提交成功'), duration: Duration(seconds: 1)),
        );
        _resetForm();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('提交失败: ${response.message}'),
            duration: Duration(seconds: 1),
          ),
        );
      }
    } catch (e) {
      print('提交复检---$e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('提交出错: $e'), duration: Duration(seconds: 1)),
      );
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 提交附件
  Future<void> _submitFile() async {
    try {
      // 获取图片信息。然后转成json数组
      final List<ImgData> imgs = context
          .read<ImageUploadNotifier>()
          .uploadedUrls;
      List<Map<String, dynamic>> jsonList = imgs
          .map((img) => img.toJson())
          .toList();
      // ImgFileData
      if (jsonList.isEmpty) {
        return;
      }

      // ImgFileData
      print('data--$jsonList');
      final res = await HttpUtil.post(
        '/storage/qualityCheckOperate/${_pendingReinspection?.id}/RECHECK/attachment/upload,',
        data: '$jsonList',
      );
      print('res--$res');
    } catch (e) {
      print('获取图片内容报错--,$e');
    }
  }

  // 重置表单方法
  void _resetForm() {
    _formKey.currentState!.reset();
    // _submitFile();
    setState(() {
      //  _carNumberController.clear();
      // 通过Provider清除上传的图片
      _focusNode3.requestFocus();
      context.read<ImageUploadNotifier>().clearAll();
    });
  }

  // 对焦
  final FocusNode _focusNode = FocusNode();

  final FocusNode _focusNode3 = FocusNode();
  final FocusNode _focusNode4 = FocusNode();
  final FocusNode _focusNode5 = FocusNode();
  // 初始化对象
  @override
  void initState() {
    super.initState();
    _pendingReinspection = PendingReinspection(
      id: '',
      qualityCheckNo: '',
      qualityCheckUserName: '',
      incomingGoodsNo: '',
      skuCode: '',
      incomingGoodsUserName: '',
      recheckNum: 0,
      pictureUrl: '',
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar:null,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(10),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 来货单号
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('质检单', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text('${_pendingReinspection?.qualityCheckNo}'),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('质检员', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '${_pendingReinspection?.qualityCheckUserName}',
                      ),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('来货单', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _qualityInspectionController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _qualityInspectionController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _qualityInspectionController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _qualityInspectionController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _focusNode,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          getInfo(context);
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: ElevatedButton(
                        onPressed: () {
                          // _getInfoRequest();
                          getInfo(context);
                        },
                        style: ElevatedButton.styleFrom(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2),
                          ),
                          backgroundColor: Colors.blue,
                          foregroundColor: Colors.white,
                          padding: EdgeInsets.all(10),
                          minimumSize: Size(0, 0),
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        ),

                        child: Text('查询'),
                      ),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('来货员', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '${_pendingReinspection?.incomingGoodsUserName}',
                      ),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),

              // SizedBox(height: 5),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child:
                          _pendingReinspection?.pictureUrl != null &&
                              _pendingReinspection!.pictureUrl!.isNotEmpty
                          ? GestureDetector(
                              onTap: () {
                                _showImagePreview(
                                  context,
                                  _pendingReinspection!.pictureUrl!,
                                );
                              },
                              child: Image(
                                image: NetworkImage(
                                  _pendingReinspection!.pictureUrl!,
                                ),
                                width: 100,
                                height: 100,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    width: 100,
                                    height: 100,
                                    color: Colors.grey[200],
                                    child: Icon(
                                      Icons.image_not_supported,
                                      size: 50,
                                      color: Colors.grey[400],
                                    ),
                                  );
                                },
                              ),
                            )
                          : Container(
                              width: 100,
                              height: 100,
                              color: Colors.grey[200],
                              child: Icon(
                                Icons.image,
                                size: 50,
                                color: Colors.grey[400],
                              ),
                            ),
                    ),
                  ),
                  Expanded(
                    flex: 4,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Expanded(
                                flex: 2,
                                child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: _buildLabel(
                                    'SKU编码',
                                    isRequired: false,
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 3,
                                child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: TextFormField(
                                    controller: _skuController,
                                    decoration: _buildInputDecoration(
                                      hintText: '',
                                      controller: _skuController,
                                      suffixIcon:
                                          ValueListenableBuilder<
                                            TextEditingValue
                                          >(
                                            valueListenable: _skuController,
                                            builder: (context, value, child) {
                                              return value.text.isEmpty
                                                  ? SizedBox.shrink()
                                                  : IconButton(
                                                      icon: Icon(
                                                        Icons.clear,
                                                        size: 20,
                                                      ),
                                                      onPressed: () {
                                                        _skuController.clear();
                                                      },
                                                    );
                                            },
                                          ),
                                    ),
                                    focusNode: _focusNode3,
                                    onFieldSubmitted: (value) {
                                      //  _getInfoRequest();
                                      getInfo(context);
                                      print('回车执行');
                                    },
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const Divider(
                            height: 2, // 容器总高度2像素
                            thickness: 1, // 分割线厚度5像素
                            indent: 0, // 左侧缩进20像素
                            endIndent: 0, // 右侧无缩进
                            color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                          ),
                          Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: _buildLabel(
                                    '应复检数量',
                                    isRequired: false,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const Divider(
                            height: 2, // 容器总高度2像素
                            thickness: 1, // 分割线厚度5像素
                            indent: 0, // 左侧缩进20像素
                            endIndent: 0, // 右侧无缩进
                            color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                          ),
                          Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: _buildLabel(
                                    '已复检数量',
                                    isRequired: false,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('复检数量', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _reInspectionController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _reInspectionController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _reInspectionController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _reInspectionController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _focusNode4,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('不良品数', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _badGoodController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _badGoodController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _badGoodController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _badGoodController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _focusNode5,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('问题描述', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(''),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('上传附件', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: ImageUploadWidget(),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('已传附件', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Column(
                        children: [
                          Consumer<ImageUploadNotifier>(
                            builder: (context, imageUploadNotifier, child) {
                              print(
                                '图片-- ${imageUploadNotifier.uploadedUrls.length}',
                              );

                              if (imageUploadNotifier.uploadedUrls.isEmpty) {
                                // ImageUploadWidgetState.notifier._uploadedUrls[0]
                                return Container(
                                  width: 100,
                                  height: 100,
                                  color: Colors.grey[200],
                                  child: Icon(Icons.image, color: Colors.grey),
                                );
                              }

                              return Wrap(
                                key: ValueKey(
                                  imageUploadNotifier.uploadedUrls.length,
                                ),
                                spacing: 8.0,
                                runSpacing: 8.0,
                                children: imageUploadNotifier.uploadedUrls.map((
                                  imgData,
                                ) {
                                  return Stack(
                                    children: [
                                      GestureDetector(
                                        onTap: () {
                                          showDialog(
                                            context: context,
                                            builder: (context) => Dialog(
                                              backgroundColor:
                                                  Colors.transparent,
                                              child: Stack(
                                                children: [
                                                  Center(
                                                    child: InteractiveViewer(
                                                      child: Image(
                                                        image: NetworkImage(
                                                          imgData.url,
                                                        ),
                                                        fit: BoxFit.contain,
                                                      ),
                                                    ),
                                                  ),
                                                  Positioned(
                                                    top: 40,
                                                    right: 20,
                                                    child: GestureDetector(
                                                      onTap: () => Navigator.of(
                                                        context,
                                                      ).pop(),
                                                      child: Container(
                                                        width: 40,
                                                        height: 40,
                                                        decoration:
                                                            BoxDecoration(
                                                              color: Colors
                                                                  .black54,
                                                              shape: BoxShape
                                                                  .circle,
                                                            ),
                                                        child: Icon(
                                                          Icons.close,
                                                          color: Colors.white,
                                                          size: 24,
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          );
                                        },
                                        child: Image(
                                          image: NetworkImage(imgData.url),
                                          width: 100,
                                          height: 100,
                                          fit: BoxFit.cover,
                                          errorBuilder:
                                              (context, error, stackTrace) {
                                                return Container(
                                                  width: 100,
                                                  height: 100,
                                                  color: Colors.grey[200],
                                                  child: Icon(
                                                    Icons.broken_image,
                                                    color: Colors.grey,
                                                  ),
                                                );
                                              },
                                        ),
                                      ),
                                      Positioned(
                                        top: 0,
                                        right: 0,
                                        child: GestureDetector(
                                          onTap: () {
                                            final index = imageUploadNotifier
                                                .uploadedUrls
                                                .indexOf(imgData);
                                            context
                                                .read<ImageUploadNotifier>()
                                                .removeUploadedUrl(index);
                                          },
                                          child: Container(
                                            width: 24,
                                            height: 24,
                                            decoration: BoxDecoration(
                                              color: Colors.red,
                                              shape: BoxShape.circle,
                                            ),
                                            child: Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 16,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  );
                                }).toList(),
                              );
                              //  return Text(imageUploadWidgetState.selectedImage!.first);
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),

              // SizedBox(height: 5),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        // 取消操作，重置表单
                        _resetForm();
                        // final formState = context
                        //     .findAncestorStateOfType<IncomingGoodsFormState>();
                        // formState?._resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

                Expanded(
                  child:
                      (_pendingReinspection?.id == null ||
                          _pendingReinspection!.id!.isEmpty)
                      ? Text('')
                      : SizedBox(
                          height: 40,
                          child: ElevatedButton(
                            onPressed: () {
                              // final formState = context
                              //     .findAncestorStateOfType<IncomingGoodsFormState>();
                              // formState?._submitForm();

                              showDialog(
                                context: context,
                                builder: (context) => AlertDialog(
                                  title: Text('确认提交'),
                                  content: Text('是否确认提交？'),
                                  actions: [
                                    TextButton(
                                      onPressed: () =>
                                          Navigator.of(context).pop(false),
                                      child: const Text('取消'),
                                    ),
                                    TextButton(
                                      onPressed: () {
                                        _submitForm();
                                        Navigator.of(context).pop(false);
                                      },
                                      child: const Text('确认'),
                                    ),
                                  ],
                                ),
                              );
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue[600],
                              foregroundColor: Colors.white,
                              textStyle: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              elevation: 3,
                              // shadowColor: Colors.blue.withOpacity(0.3),
                            ),
                            child: const Text('提交'),
                          ),
                        ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showImagePreview(BuildContext context, String imageUrl) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Stack(
            children: [
              Center(
                child: InteractiveViewer(
                  panEnabled: true, // 允许拖拽
                  boundaryMargin: EdgeInsets.all(20),
                  minScale: 0.1,
                  maxScale: 6.0,
                  child: SizedBox(
                    width: MediaQuery.of(context).size.width * 0.9,
                    child: Image.network(
                      imageUrl,
                      fit: BoxFit.contain,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          padding: EdgeInsets.all(20),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.error, size: 50, color: Colors.white),
                              SizedBox(height: 10),
                              Text(
                                '图片加载失败',
                                style: TextStyle(color: Colors.white),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 40,
                right: 20,
                child: GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(Icons.close, color: Colors.white, size: 24),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 构建标签文本
  Widget _buildLabel(String text, {bool isRequired = false}) {
    return SizedBox(
      // width: 200,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 8),
        child: Text(
          text,
          style: TextStyle(
            fontWeight: FontWeight.w500,
            fontSize: 16,
            color: isRequired ? Colors.red : Colors.grey[700],
          ),
        ),
      ),
    );
  }

  // 构建输入框装饰
  InputDecoration _buildInputDecoration({
    required String hintText,
    required TextEditingController controller,
    Widget? suffixIcon,
  }) {
    print('controller ${controller.text}');
    return InputDecoration(
      hintText: hintText,
      contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
      // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
      suffixIcon: suffixIcon,
      hintStyle: TextStyle(color: Colors.grey[500]),
      // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
      // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
      // 适用于需要节省空间或创建更紧凑布局的场景
      // isDense: true,
      filled: true,
      fillColor: Colors.grey[50],

      // suffixIcon: controller.text.isNotEmpty
      //             ? IconButton(
      //                 icon: Icon(Icons.clear, size: 20),
      //                 onPressed: () {
      //                   controller.clear();
      //                   // 需要通知父组件状态更新
      //                   if (mounted) {
      //                     setState(() {});
      //                   }
      //                 },
      //               )
      //             : null,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.blue, width: 2),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.red),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.red, width: 2),
      ),
    );
  }
}

// 构建一个对象
class PendingReinspection {
  final String? id;
  final String? qualityCheckNo;
  final String? qualityCheckUserName;
  final String? incomingGoodsNo;
  final String? incomingGoodsUserName;
  final String? skuCode;
  final num? recheckNum;
  final String? pictureUrl;
  final num? recheckDefectiveNum;
  final String? recheckProblemDesc;
  PendingReinspection({
    this.id,
    this.qualityCheckNo,
    this.qualityCheckUserName,
    this.incomingGoodsNo,
    this.incomingGoodsUserName,
    this.skuCode,
    this.recheckNum,
    this.pictureUrl,
    this.recheckDefectiveNum,
    this.recheckProblemDesc,
  });
  factory PendingReinspection.form(Map<String, dynamic> json) {
    return PendingReinspection(
      id: json['id'] as String?,
      qualityCheckNo: json['qualityCheckNo'] as String?,
      qualityCheckUserName: json['qualityCheckUserName'] as String?,
      incomingGoodsNo: json['incomingGoodsNo'] as String?,
      incomingGoodsUserName: json['incomingGoodsUserName'] as String,
      skuCode: json['skuCode'] as String,
      recheckNum: json['recheckNum'] as num,
      pictureUrl: json['pictureUrl'] as String,
      recheckDefectiveNum: json['recheckDefectiveNum'] as num,
      recheckProblemDesc: json['recheckProblemDesc'] as String,
    );
  }
}
